package com.zdft.promotion.common.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.UUID;

/**
 * Excel工具类
 *
 * @author wcy
 * @date 2019年2月27日15:19:22
 */
@Component
public class ExcelUtil {

    public static Logger logger = LoggerFactory.getLogger(ExcelUtil.class);

    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,
                                   String fileName, boolean isCreateHeader, HttpServletResponse response) {
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }

    /**
     * @param list
     * @param title
     * @param sheetName
     * @param pojoClass
     * @param fileName  <span>
     *                  moduleType:1、生产厂家主档 2、商品主档 3、供应商主档 4、客户主档" 5、供应商商品
     *                  createUser:操作人工号
     *                  createUserName:操作人名称
     *                  queryParam:导出数据筛选参数
     *                  </span>
     * @param response
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName,
                                   HttpServletResponse response) {
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }

    public static void export07Excel(List<?> list, Class<?> pojoClass, String fileName,
                                     HttpServletResponse response, ExportParams params) {
        if (params == null) {
            params = getDefaultExportParams();
        }
        defaultExport(list, pojoClass, fileName, response, params);
    }

    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        defaultExport(list, fileName, response);
    }

    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName,
                                      HttpServletResponse response, ExportParams exportParams) {
        Integer count = list.size();
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        if (workbook != null) {
            downLoadExcel(fileName, response, workbook);
        }
    }

    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
//            response.setContentType("APPLICATION/OCTET-STREAM")
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            //throw new NormalException(e.getMessage());
        }
    }

    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (workbook != null) {
        }
        downLoadExcel(fileName, response, workbook);
    }

    public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        } catch (NoSuchElementException e) {
            //throw new NormalException("模板不能为空");
        } catch (Exception e) {
            e.printStackTrace();
            //throw new NormalException(e.getMessage());
        }
        return list;
    }

    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
        if (file == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        } catch (NoSuchElementException e) {
            // throw new NormalException("excel文件不能为空");
        } catch (Exception e) {
            //throw new NormalException(e.getMessage());
            System.out.println(e.getMessage());
        }
        return list;
    }

    public static <T> ExcelImportResult<T> importExcelWithError(MultipartFile file, Class<T> pojoClass, ImportParams importParams) {
        if (file == null) {
            return null;
        }
        if (importParams == null) {
            importParams = getDefaultImportParams();
        }
        ExcelImportResult<T> result = null;
        try {
            result = ExcelImportUtil.importExcelMore(file.getInputStream(), pojoClass, importParams);
        } catch (NoSuchElementException e) {
            // throw new NormalException("excel文件不能为空");
            logger.error(e.getMessage());
        } catch (Exception e) {
            //throw new NormalException(e.getMessage());
            logger.error(e.getMessage());
        }
        return result;
    }

    private static ExportParams getDefaultExportParams() {
        ExportParams exportParams = new ExportParams();
        exportParams.setType(ExcelType.XSSF);
        return exportParams;
    }

    /**
     * 获取默认参数
     *
     * @return
     */
    private static ImportParams getDefaultImportParams() {
        ImportParams params = new ImportParams();
        params.setNeedVerfiy(true);
        params.setTitleRows(0);
        params.setHeadRows(1);
        return params;
    }

    public static <T> ExcelImportResult<T> importExcelWithError(File file, Class<T> pojoClass) {
        if (file == null) {
            return null;
        }
        ImportParams params = getDefaultImportParams();
        ExcelImportResult<T> result = null;
        try {
            result = ExcelImportUtil.importExcelMore(file, pojoClass, params);
        } catch (NoSuchElementException e) {
            // throw new NormalException("excel文件不能为空");
            logger.error(e.getMessage());
        } catch (Exception e) {
            //throw new NormalException(e.getMessage());
            logger.error(e.getMessage());
        }
        return result;
    }


    public static <T> ExcelImportResult<T> importExcelWithError(MultipartFile file, Class<T> pojoClass) {
        if (file == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setNeedVerfiy(true);
        params.setTitleRows(0);
        params.setHeadRows(1);
        params.setKeyIndex(null);
        ExcelImportResult<T> result = null;
        try {
            result = ExcelImportUtil.importExcelMore(file.getInputStream(), pojoClass, params);
        } catch (NoSuchElementException e) {
            // throw new NormalException("excel文件不能为空");
            logger.error(e.getMessage());
        } catch (Exception e) {
            //throw new NormalException(e.getMessage());
            logger.error(e.getMessage());
        }
        return result;
    }

    /**
     * workbook保存为excel
     *
     * @param pathPrix
     * @param workbook
     * @throws IOException
     */
    public static String saveExcel(String pathPrix, Workbook workbook) {
        String errorId = UUID.randomUUID().toString();
        String partPath = FileUtil.getFileName(pathPrix, errorId + ".xlsx");
        String filePath = pathPrix + File.separator + partPath;
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(partPath);
            workbook.write(fileOutputStream);
            fileOutputStream.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return partPath;
    }

    public static String saveHttpResExcel(String pathPrix, Workbook workbook) {
        String errorId = UUID.randomUUID().toString();
        String partPath = FileUtil.getPartFileName(pathPrix, errorId + ".xlsx");
        String filePath = pathPrix + File.separator + partPath;
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(filePath);
            workbook.write(fileOutputStream);
            fileOutputStream.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return partPath;
    }
}
